#pragma once

#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <cerrno>
#include "log.hpp"
#include "err.hpp"

class ns_client
{
public:
    ns_client(std::string serverIp, uint16_t serverPort)
        : _sock(-1), _serverIp(serverIp), _serverPort(serverPort)
    {
    }

    void init()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            LogMessage(Debug, "creat sock fail");
            exit(SOCK_ERR);
        }
        LogMessage(Debug, "creat sock success");
    }

    void start()
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = inet_addr(_serverIp.c_str());
        local.sin_port = htons(_serverPort);
        int cnt = 1;
        while (connect(_sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LogMessage(Debug, "connect fail,it is reconnecting now,This is %d time", cnt++);
            if (cnt == 5)
            {
                break;
            }
        }
        if (cnt == 5)
        {
            LogMessage(Error, "connect fail , errno : %d , error : %s", errno, strerror(errno));
            exit(CONNECT_ERR);
        }
        LogMessage(Debug, "connect sucess");
        while (true)
        {
            std::string message;
            getline(std::cin, message);
            int n = write(_sock, message.c_str(), message.size());
            if (n < 0)
            {
                LogMessage(Warning, "write fail");
                exit(WRITE_ERR);
            }
            char buffer[1024];
            n = read(_sock, buffer, sizeof(buffer) - 1);
            if (n < 0)
            {
                LogMessage(Warning, "read fail");
                exit(READ_ERR);
            }
            buffer[n] = '\0';
            std::cout << "server send message : " << buffer << std::endl;
        }
    }

    ~ns_client()
    {
    }

private:
    int _sock;
    std::string _serverIp;
    uint16_t _serverPort;
};